package com.lap.auth.filter;

import com.lap.auth.application.authorization.dto.ApiDto;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

public class PermissionMatcher {

  private static final String BLANK = "";
  private static final String SLASH = "/";
  private static final String REPLACE_PATTERN = "[\\\\w+\\\\.*]+";
  private static final String REGEX = "\\{\\w+}";
  private static final Pattern PATTERN = Pattern.compile(REGEX);

  public Optional<ApiDto> match(List<ApiDto> apis, String uri, String method) {
    if (apis == null || apis.isEmpty()) {
      return Optional.empty();
    }

    return apis.stream()
        .filter(
            api -> {
              String patternUri = resolvePattern(api);
              return Pattern.matches(patternUri, uri) && method.equalsIgnoreCase(api.getMethod());
            })
        .findFirst();
  }

  private String resolvePattern(ApiDto api) {
    StringBuilder result = new StringBuilder();
    if (StringUtils.isNotBlank(api.getUri())) {
      result.append(api.getUri().startsWith(SLASH) ? BLANK : SLASH).append(api.getUri());
    }
    return PATTERN.matcher(result.toString()).replaceAll(REPLACE_PATTERN);
  }
}
